<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="changeValue"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="treeDept"
          node-key="id"
          :default-checked-keys="[1]"
          :data="depts"
          :props="defaultProps"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          @current-change="selectedNode"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'addEmployee'" size="mini" type="primary" @click="$router.push({name: 'DetailPage'})">添加员工</el-button>
          <el-button v-permission="'importEmployee'" size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button v-permission="'excelEmployee'" size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="employeeList">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template v-slot="{ row }">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" sortable prop="mobile" />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template v-slot="{ row }">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="操作" width="280px">
            <template v-slot="{ row }">
              <el-button size="mini" type="text" @click="$router.push({name: 'DetailPage', params: {id: row.id}})">查看</el-button>
              <el-button size="mini" type="text" @click="btnRole(row.id)">角色</el-button>
              <el-popconfirm title="确认删除该行数据吗？" @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total,prev, pager, next"
            :total="total"
            :page-size.sync="queryParams.pagesize"
            :current-page.sync="queryParams.page"
            @current-change="getEmployeeList"
          />
        </el-row>
      </div>
    </div>
    <ImportExcel :show-excel-dialog.sync="showExcelDialog" @updateEmployee="getEmployeeList" />
    <el-dialog :visible.sync="isRoleDialog" title="分配角色">
      <!-- 弹层内容 -->
      <!-- checkbox -->
      <el-checkbox-group v-model="roleIds">
        <!-- 放置n个的checkbox  要执行checkbox的存储值 item.id-->
        <el-checkbox
          v-for="v of roleList"
          :key="v.id"
          :label="v.id"
        >{{ v.name }}</el-checkbox>
      </el-checkbox-group>
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="small" type="primary" @click="okRles">确定</el-button>
          <el-button size="small" @click="isRoleDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
// 导入封装好的组件-上传文件组件
import ImportExcel from './components/import-excel.vue'
// 导入 FileSaver
import FileSaver from 'file-saver'
// 导入 部门信息
import { getDepartments } from '@/api/department.js'
// 导入 列表型数据转化树形的递归函数
import { transListToTreeData } from '@/utils/index.js'
// 导入 员工管理
import { getEmployeeList, putEmployeeRoles, exportEmployee, delEmployee, getEnableRoleList, getEmployeeDetail } from '@/api/employee.js'
export default {
  name: 'EmployeePage',
  components: {
    ImportExcel
  },
  data() {
    return {
      isRoleDialog: false, // 用来控制角色弹层的显示
      roleList: [], // 接收角色列表
      roleIds: [], // 用来双向绑定数据的
      employeeId: null, // 存储选中员工ID
      showExcelDialog: false,
      timer: null, // 清除定时器
      employeeList: [],
      // queryParams 对象是用来查询的参数
      queryParams: {
        page: 1,
        pagesize: 5,
        keyword: '',
        // departmentId 记录当前选中的部门编号
        departmentId: null
      },
      total: 0, // 员工的总数
      depts: [], // 部门列表数据
      defaultProps: {
        label: 'name',
        children: 'children'
      }

    }
  },
  async created() {
    await this.getDepartments()
    await this.getEmployeeList()
  },
  methods: {
    async okRles() {
      await putEmployeeRoles({
        id: this.employeeId,
        roleIds: this.roleIds
      })
      this.$message.success('分配角色成功')
      this.isRoleDialog = false
    },
    // 角色按钮弹出弹层，给员工分配角色功能
    async btnRole(id) {
      this.roleList = await getEnableRoleList()
      const { roleIds } = await getEmployeeDetail(id)
      console.log(roleIds, '角色详情')
      this.roleIds = roleIds
      this.isRoleDialog = true
      this.employeeId = id
    },
    // 删除员工方法
    async confirmDel(id) {
      await delEmployee(id)
      if (this.employeeList.length === 1 && this.queryParams.page > 1) this.queryParams.page--
      this.$message.success('删除员工成功')
      this.getEmployeeList()
    },
    // 导出 xlsx 功能
    async exportEmployee() {
      const res = await exportEmployee() // 导出所有员工接口调用
      FileSaver.saveAs(res, '员工信息表.xlsx') // 下载文件
    },

    // 搜索功能_防抖处理
    changeValue() {
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployeeList()
      }, 500)
    },
    // 获取员工列表
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.queryParams)
      console.log({ rows, total }, 'rows, total')
      this.employeeList = rows
      this.total = total
      console.log(this.employeeList, '员工列表')
    },
    // 获取部门列表
    async getDepartments() {
      const res = await getDepartments()
      // 封装好的递归函数 列表型数据转化树形
      this.depts = transListToTreeData(res, 0)
      console.log(this.depts, 'depts')
      // 设置默认的部门id
      this.queryParams.departmentId = this.depts[0].id
      // 等到树状结构加载渲染完毕之后，再设置默认选中向
      this.$nextTick(() => {
        // 设置默认选中项
        this.$refs.treeDept.setCurrentKey(this.queryParams.departmentId)
      })
    },
    async selectedNode(v) {
      // 保存当前用户点击的部门的id
      this.queryParams.departmentId = v.id
      this.queryParams.page = 1 // 重置第一页
      await this.getEmployeeList()
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
  ::v-deep .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
    color: #276ffb;
    background-color: #f0f4ff;
  }
}

</style>
